<!-- eslint-disable no-unreachable -->
<template>
  <div>

    <el-container>
      <!-- 搜索栏 -->
      <el-header>
        <el-row :gutter="20" style="padding: 5px 20px;">
          <el-col :span="6"><el-input v-model="searchModel.roleName" placeholder="角色名称" clearable @keyup.enter.native="getRoleList" /></el-col>
          <el-col :span="6"><el-button type="primary" round icon="el-icon-search" @click="getRoleList">搜索</el-button></el-col>
          <el-col align="right" :span="6"><el-button type="primary" round icon="el-icon-plus" @click="handleDialogVisible(null)">新增</el-button></el-col>
        </el-row>
      </el-header>

      <!-- 结果列表 -->
      <el-main>
        <el-table :data="roleList" style="width: 100%">
          <el-table-column type="index" label="index" width="180">
            <template slot-scope="scope">
              {{ (searchModel.pageNo - 1) * searchModel.pageSize + scope.$index + 1 }}
            </template>
          </el-table-column>
          <el-table-column prop="roleId" label="角色编号" width="180" />
          <el-table-column prop="roleName" label="角色名" width="180" />
          <el-table-column prop="roleDesc" label="角色描述" />
          <el-table-column label="操作">
            <template slot-scope="scope">
              <el-button
                size="mini"
                icon="el-icon-edit"
                @click="handleDialogVisible(scope.row.roleId)"
              >修改</el-button>
              <el-button
                size="mini"
                type="danger"
                icon="el-icon-delete"
                @click="deleteRole(scope.row)"
              >删除</el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-main>

      <!-- 分页 -->
      <el-footer>
        <el-pagination
          :current-page="searchModel.pageNo"
          :page-sizes="[5, 10, 20, 50]"
          :page-size="searchModel.pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="totalPage"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </el-footer>
    </el-container>

    <!-- 修改框 -->
    <el-dialog :title="title" :visible.sync="dialogFormVisible" @close="clearForm">
      <el-form ref="roleFormRef" :model="roleForm" :rules="rules">
        <el-form-item prop="roleName" label="角色名称" :label-width="formLabelWidth">
          <el-input v-model="roleForm.roleName" autocomplete="off" />
        </el-form-item>
        <el-form-item prop="roleDesc" label="角色描述" :label-width="formLabelWidth">
          <el-input v-model="roleForm.roleDesc" autocomplete="off" />
        </el-form-item>
        <el-form-item prop="menuIdList" label="权限设置" :label-width="formLabelWidth">
          <el-tree
            ref="menuRef"
            :data="menuList"
            :props="menuProps"
            show-checkbox
            default-expand-all
            style="width: 70%;"
            node-key="menuId"
          />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="handleSave">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import menuRequest from '@/api/menuManage'
import roleRequest from '@/api/roleManage'
export default {
  data() {
    return {
      totalPage: 0,
      searchModel: {
        roleName: '',
        pageNo: 1,
        pageSize: 10
      },
      roleList: [],
      dialogFormVisible: false, // 对话框显示隐藏
      roleForm: {
        roleName: '',
        roleDesc: ''
      },
      formLabelWidth: '150px',
      title: '',
      rules: {
        roleName: [
          { required: true, message: '请输入角色名', trigger: 'blur' },
          { min: 2, max: 20, message: '长度在 2 到 20 个字符', trigger: 'blur' }
        ],
        roleDesc: [
          { required: true, message: '请输入角色描述', trigger: 'blur' },
          { min: 2, max: 20, message: '长度在 2 到 20 个字符', trigger: 'blur' }
        ]
      },
      menuProps: {
        chridren: 'children',
        label: 'title'
      },
      menuList: []
    }
  },
  created() {
    this.getRoleList()
    this.getAllRole()
  },
  methods: {
    getAllRole() {
      menuRequest.getAllMenu().then((response) => {
        this.menuList = response.data
      })
    },
    handleSizeChange(pageSize) {
      this.searchModel.pageSize = pageSize
      this.getRoleList()
    },
    handleCurrentChange(pageNo) {
      this.searchModel.pageNo = pageNo
      this.getRoleList()
    },
    getRoleList() {
      // then是调完后的回调方法
      // 在then中把数据传回过来, total 和 list要复制
      roleRequest.getRoleList(this.searchModel).then(response => {
        this.totalPage = response.data.totalPage
        this.roleList = response.data.rows
      })
    },
    handleDialogVisible(id) {
      if (id == null) {
        this.title = '新增用户'
      } else {
        this.title = '修改用户'
        roleRequest.getRoleById(id).then(response => {
          this.roleForm = response.data
          this.$refs.menuRef.setCheckedKeys(response.data.menuIdList)
        })
      }

      this.dialogFormVisible = true
    },
    clearForm() {
      this.roleForm = {}
      this.$refs.roleFormRef.clearValidate()
      this.$refs.menuRef.setCheckedKeys([])
    },
    handleSave() {
      // 触发表单验证
      this.$refs.roleFormRef.validate((valid) => {
        if (valid) {
          // 返回被选中的key的数组
          // eslint-disable-next-line prefer-const
          let checkedKeys = this.$refs.menuRef.getCheckedKeys()
          // eslint-disable-next-line prefer-const
          let halfCheckedKeys = this.$refs.menuRef.getHalfCheckedKeys()
          this.roleForm.menuIdList = checkedKeys.concat(halfCheckedKeys)
          console.log(this.roleForm.menuIdList)
          // 提交后台处理
          // eslint-disable-next-line no-unreachable
          roleRequest.saveRole(this.roleForm).then(response => {
            // 成功提示
            this.$message({
              message: response.message,
              type: 'success'
            })
            // 关闭表格
            this.dialogFormVisible = false
            // 刷新表格
            this.getRoleList()
          })
        } else {
          console.log('error submit!!')
          return false
        }
      })
    },
    deleteRole(role) {
      this.$confirm('此操作将删除该角色, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        roleRequest.deleteRoleById(role.roleId).then(response => {
          this.$message({
            type: 'success',
            message: response.message
          })
          this.getRoleList()
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
      })
    }
  }
}
</script>

<style>
  .el-dialog .el-input {
    width: 70%;
  }
</style>
